package com.dai.designpattern.prototype.practice;

import com.dai.designpattern.prototype.practice.constant.SceneNameCode;
import com.dai.designpattern.prototype.practice.mold.SceneMatchWord;

import java.io.*;
import java.util.LinkedList;

/**
 * 场景超类
 * @author daijiyong
 */
abstract public class AbstractScene implements Cloneable, Serializable {
    /**
     * 场景名字
     */
    public SceneNameCode sceneNameCode;

    /**
     * 当前场景的匹配词
     */
    protected LinkedList<SceneMatchWord> matchWords;


    public AbstractScene() {
    }

    public AbstractScene(SceneNameCode sceneNameCode) {
        this.sceneNameCode = sceneNameCode;
    }


    /**
     * 对外统一处理操作，子类进行重写
     */
    public abstract String deal(String userInput);

    /**
     * 初始化操作，子类进行重写
     */
    protected abstract void init();

    /**
     * 根据用户输入与当前场景进行匹配
     *
     * @param userInput 用户输入内容
     * @return 匹配结果
     */
    public Boolean match(String userInput) {

        // TODO
        //  根据用户的输入进行匹配
        //  匹配成功则返回true，失败则返回false
        for (SceneMatchWord smw : matchWords) {
            if (smw.match(userInput)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 深克隆
     *
     * @return 克隆结果
     */
    @Override
    public AbstractScene clone() {
        AbstractScene clone = null;
        try {
            clone = (AbstractScene) super.clone();
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bo);
            oos.writeObject(this);
            ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
            ObjectInputStream oi = new ObjectInputStream(bi);
            clone = (AbstractScene) oi.readObject();
        } catch (IOException | ClassNotFoundException | CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }
}
